package win.smartown.android.app.redrain;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.FrameLayout;

/**
 * Created by Smartown on 2017/7/26.
 */
public class RedRainContainer extends FrameLayout {

    private Handler handler = new Handler();
    private float fromSize = 1f / 5f;
    private float toSize = 1f / 12f;
    private int totalCount = 30;
    private long duration = 50;
    private long distance =1500;
    private float angle = -15;

    public RedRainContainer(@NonNull Context context) {
        super(context);
        setVisibility(GONE);
    }

    public RedRainContainer(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setVisibility(GONE);
    }

    public RedRainContainer(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setVisibility(GONE);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public RedRainContainer(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        setVisibility(GONE);
    }

    private int count = 0;

    public void start() {
        if (getVisibility() == VISIBLE) {
            return;
        }
        setVisibility(VISIBLE);
        addRain();
    }

    private void addRain() {
        if (count >= totalCount) {
            return;
        }
        count++;
        RedRainImageView redRainImageView = new RedRainImageView(getContext());
        int startSize = (int) (getWidth() * fromSize);
        int deltaX = (int) ((getWidth() + startSize) * Math.tan(angle * Math.PI / 180));
        int deltaY = getHeight() + startSize;
        redRainImageView.setLayoutParams(new ViewGroup.LayoutParams(startSize, startSize));
        redRainImageView.setImageResource(R.mipmap.red_rain);
        redRainImageView.setParameters(count, distance, deltaX, deltaY, toSize / fromSize, new RedRainImageView.Callback() {
            @Override
            public void onAnimFinished(RedRainImageView view, int index) {
                removeView(view);
                if (index == totalCount) {
                    count = 0;
                    setVisibility(GONE);
                }
            }
        });
        redRainImageView.setTranslationX((int) (Math.random() * getWidth()));
        redRainImageView.setTranslationY(-startSize);
        addView(redRainImageView);
        redRainImageView.startAnimation();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                addRain();
            }
        }, duration);
    }

}
